/**
 * 消息
 */
$(document).ready(function(e) {	
	initialSpace();
	initialRole();
	search(0);
	initialClientLevle();
})

function initailPageNumber(totalPage,currentPage,pageLength){
	try{
			var midNumber = Math.ceil((pageLength-2)/2);
			var paginList = $(".paginList");
			$(paginList).empty();			
			var prev = '<li class="paginItem"><a href="javascript:;"><span class="pagepre"></span></a></li>';
			var next = '<li class="paginItem"><a href="javascript:;"><span class="pagenxt"></span></a></li>';
			if( totalPage <= pageLength - 2){
				$(prev).appendTo($(".paginList"));
				for(var i = 1; i<totalPage+1; i++){
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
					if(i == currentPage){
						pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
					}			
					$(pagenItem).appendTo($(".paginList"));
				}
				$(next).appendTo($(".paginList"));
			}else{				
				if(currentPage <= midNumber){
					$(prev).appendTo($(".paginList"));
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
						if(i == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
						}			
						$(pagenItem).appendTo($(".paginList"));
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}if(totalPage - currentPage < midNumber){

					var index = totalPage;
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+index+'</a></li>';
						if(index == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+index+'</a></li>';
						}			
						$(pagenItem).prependTo($(".paginList"));
						index--;
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+ 1 +'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					$(next).appendTo($(".paginList"));
				}else if(totalPage - currentPage >= midNumber && currentPage > midNumber){

					pagenItem = '<li class="paginItem current"><a href="javascript:;">'+currentPage+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					var count = midNumber - 3;
					for(var i = 1; i<=count;i++){
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage-i)+'</a></li>';
						$(pagenItem).prependTo($(".paginList"));
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage+i)+'</a></li>';
						$(pagenItem).appendTo($(".paginList"));
					}
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+1	+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}				
			}
			$(".paginItem").click(function(){
				if($(this).hasClass("more")){
					//alert("more");
					return;
				}else if($(this).find(".pagepre").length > 0){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur > 1){
						search(cur - 1);
					}
				}else if($(this).find(".pagenxt").length > 0 ){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur < totalPage){
						search(cur + 1);
					}
				}else{
					var cur = $(this).find("a").html();
					cur = parseInt(cur);
					search(cur);
				}
			});
	}catch(e){/*alert(e.messge);*/}	
}
function getSearchParameter(currentPage){
	try{
		var searchTitle= $("#searchTitle").val();	
		var searchArea = parseInt($("#searchArea").val());
		var searchType = parseInt($("#searchType").val());
		if(!currentPage) currentPage=1;
		if(searchType==0){
			var requestJson = {currentPage:parseInt(currentPage),data:{title:searchTitle,userAreaId:searchArea,userType:null}};
		}else{
			var requestJson = {currentPage:parseInt(currentPage),data:{title:searchTitle,userAreaId:searchArea,userType:searchType}};	
		}
		
		
		return requestJson;
	}catch(e){
		console.log(e.messge);
	}
	return false;	
}
function initialSpace(){
	try{
		var spaceString = localStorage.getItem('space');
		spaces = $.parseJSON(spaceString);
	}catch(e){
		console.log(e.messge);
	}
	$.ajax({
        url: '/euc/system/space',
        data:'',
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	try{
	        	$.each(result,function(index,data){	
	        		spaces[data.id] = data;  
	   			});
	        	var spaceJson = JSON.stringify(spaces);
	        	localStorage.setItem('space',spaceJson);
        	}catch(e){
        		/*alert(e.message);*/
        	}
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
	var spaceSelect = $("#searchArea");	
	var addSelect = $("#addArea");	
	$.each(spaces,function(key,space){	
		if(space.id ==1){
			$('<option value="'+ space.id +'" selected>'+ space.spaceName +'</option>').appendTo($(spaceSelect));
			$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(addSelect));
		}else{
			$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceSelect));
			$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(addSelect));
		}

	});
	
}
function initialRole(){
	try{
		var roleString = localStorage.getItem('rolestype');
		roles = $.parseJSON(roleString);
	}catch(e){
		console.log(e.messge);
	}
	$.ajax({
        url: '/euc/role/all',
        data:'{"currentPage":1,"data":{"roleName":"","roleType":""}}',
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	rolesData=new Array();
        	try{
        		$.each(result,function(i,data){
        			rolesData[data["id"]]=data;

        		})

	        	var roleJson = JSON.stringify(rolesData);
	        	localStorage.setItem('rolestype',roleJson);
	        	roles =rolesData;
	        	
        	}catch(e){
        		/*alert(e.message);*/
        	}
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
	var roleSelect = $("#searchType");	

	$.each(roles,function(key,role){	
		if(role){
			$('<option value="'+ role.id +'">'+ role.roleName +'</option>').appendTo($(roleSelect));
			html = '<input name="addUserType" type="checkbox" value="'+ role.id +'" /> '+ role.roleName;
			$("#rolelist").append(html);
			
		}   		
	});
}

function search(currentPage){

	var requestJson = getSearchParameter(currentPage);
	if(requestJson == false){
		return false;
	}
	$.ajax({
        url: '/euc/onlineops/msg/query',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	//alert(JSON.stringify(result));
        	pageBean = result.data;
        	$("#userTable").empty();	        	
        	$.each(result.data.list,function(i,data){
        		       		

        		var bgcolor= localStorage.getItem('trcolor');
        		if(i % 2 == 0){
        			bgcolor = '';
        		}
        		var  content =decodeURI($.trim(data["content"]));
        		var html = '<tr '+ bgcolor +'>';
        		html += '<td>' + (i+1) + '</td>';
        		html += '<td>' + $.trim(data["title"]) + '</td>';
        		html += '<td><div style="height:35px;">' + content + '</div></td>';
        		html += '<td>' + data.userArea + '</td>';
        		//html += '<td>' + roleTypeName + '</td>';
        		html += '<td>' + data.createPerson + '</td>';
        		html += '<td>' + data.modTime + '</td>';
              		html += '<td style="width:170px;"><a href="javascript:detail('+data.id+');" class="tablelink">详情</a>&nbsp;&nbsp;&nbsp;<a href="javascript:deleteData('+data.id+');" class="tablelink">删除</a></td>';
        		html += '</tr>';
	        	$("#userTable").append(html);
	        	//dataList[data.id] = data;
			});
        	$("#totalRow").html(pageBean.totalRow+'&nbsp;');
        	$("#currentPage").html(pageBean.currentPage+'&nbsp;');
        	$("#pageSize").html(pageBean.pageSize+'&nbsp;');        	
        	var pageLength = 15;
        	initailPageNumber(pageBean.totalPage,pageBean.currentPage,pageLength);        	
        },
        error: function () {
        	console.log("error");
        }  
    });
}

function deleteData(id){
	 if(confirm("确定删除该详情?")){
		$.ajax({
	        url: '/euc/onlineops/msg/delete',
	        data:'{"data":{"id":'+id+'}}',
	        beforeSend: function(request) {
	        	var accessToken = localStorage.getItem('accessToken');
	            request.setRequestHeader("accessToken",accessToken );
	        },
	        dataType: 'JSON',
	        async: true,
	        contentType:'application/json;charset=utf-8',
	        type: 'POST',
	        success: function (result, textStatus, response) {
	        	var cur = $('.paginItem.current').find("a").html();
				cur = parseInt(cur);
				search(cur);
				alert(result.message);
	        },
	        error: function () {
	        	console.log("error");
	        }  
	    });
	 }
}

function detail(id){
	$("DIV[name='msgList']").hide();
	$("DIV[name='AddMsg']").hide();	
	$("DIV[name='viewInfo']").show();	

	$.ajax({
        url: '/euc/onlineops/msg/detail',
        data:'{"data":{"id":'+id+'}}',
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	//alert(JSON.stringify(result));
        	//var clientLevle = $("SELECT[name='clientLevle']");     
        
        	data=result.data;
        	var roleTypeName = '';
    		if(data.tagretType==1){
    			roleTypeName = '所有人';
    		}else if(data.tagretType==2){
    			
    			if($.trim(data["tagretInfo"]) != ''){
        			if(data["tagretInfo"].indexOf("|")>0){
        				$tars=data["tagretInfo"].split("|");
        				$.each($tars,function(k,v){
        					var name=roles[v];
                			roleTypeName += name ? name.roleName+' ' : '';
        				})
        				
        			}else{
        				var name=roles[data["tagretType"]];
            			roleTypeName = name ? name.roleName : '';
        			}
        		}
    		}else if(data.tagretType==3){
    			roleTypeName = '特定用户';
    		}else if(data.tagretType==4){
    			roleTypeName = '用户分组';
    		}
        	
        	
        	$html='<li><label>标题</label>'+data.title+'</li>'
        	$html+='<li><label>内容</label>'+decodeURI(data.content)+'</li>'
        	$html+='<li><label>发布时间</label>'+data.addTime+'</li>'
        	$html+='<li><label>用户区域</label>'+data.userArea+'</li>'
        	$html+='<li><label>目标类型</label>'+roleTypeName+'</li>'
        	$html+='<li><label>发布人</label>'+data.createPerson+'</li>'
           	$("#msgViewInfo").html($html);
   			
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
}
function initialClientLevle(){
	$.ajax({
        url: '/euc/client/activeclient',
        data:'',//JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	//alert(JSON.stringify(result));
        	var clientLevle = $("#addUserClient");        	
        	$.each(result,function(index,data){	
        		if(data.clientType=="企业"){
        			$('<option value="'+ data.id +'">'+ data.companyName +'</option>').appendTo($(clientLevle));
        		}else{
        			$('<option value="'+ data.id +'">'+ data.memberName +'</option>').appendTo($(clientLevle));
        		}
           		//clientLevles[data.id] = data;
   			});
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
}
